﻿using Autofac;
using Autofac.Core;
using Autofac.Extensions.DependencyInjection;
using Common.Config;
//using Microsoft.AspNetCore.Authentication.JwtBearer;
using Microsoft.AspNetCore.Authorization;
using Microsoft.IdentityModel.Tokens;
using Model;
using Newtonsoft.Json;
using System.Text;
using WebApi.Filter;

namespace WebAPI.Config
{
    /// <summary>
    /// 扩展类
    /// </summary>
    public static class HostBuilderExtend
    {
        public static void Register(this WebApplicationBuilder builder)
        {
            //注册日志服务
            builder.Logging.AddLog4Net("Config/log4net.Config");

            
            //注入autofac
            builder.Host.UseServiceProviderFactory(new AutofacServiceProviderFactory())
                .ConfigureContainer<ContainerBuilder>(builder =>
                {
                    builder.RegisterModule(new AutofacModuleRegister());
                    
                });

            //注册automapper
            builder.Services.AddAutoMapper(typeof(AutoMapperConfigs));


            //第一步，注册JWT
            //builder.Services.Configure<JWTTokenOptions>(builder.Configuration.GetSection("JWTTokenOptions"));
            //#region JWT校验
            ////第二步，增加鉴权逻辑
            //JWTTokenOptions tokenOptions = new JWTTokenOptions();
            //builder.Configuration.Bind("JWTTokenOptions", tokenOptions);
            //builder.Services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)//Scheme
            // .AddJwtBearer(options =>  //这里是配置的鉴权的逻辑
            // {
            //     options.TokenValidationParameters = new TokenValidationParameters
            //     {
            //         //JWT有一些默认的属性，就是给鉴权时就可以筛选了
            //         ValidateIssuer = true,//是否验证Issuer
            //         ValidateAudience = true,//是否验证Audience
            //         ValidateLifetime = true,//是否验证失效时间
            //         ValidateIssuerSigningKey = true,//是否验证SecurityKey
            //         ValidAudience = tokenOptions.Audience,//
            //         ValidIssuer = tokenOptions.Issuer,//Issuer，这两项和前面签发jwt的设置一致
            //         IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(tokenOptions.SecurityKey))//拿到SecurityKey 
            //     };
            // });
            //#endregion

            ////添加跨域策略
            builder.Services.AddCors(options =>
            {
                options.AddPolicy("CorsPolicy", opt =>
                opt.WithOrigins("http://localhost:8080")
                .AllowAnyHeader()
                .AllowAnyMethod()
                //.WithExposedHeaders("X-Pagination")
                );
            });
            
            builder.Services.AddControllers(options =>
            {
                //注入异常过滤器
                options.Filters.Add(new CustomerExceptionFilter());

            }).AddNewtonsoftJson(options =>
            {
                ////设置Json返回的日期格式
                options.SerializerSettings.ReferenceLoopHandling = ReferenceLoopHandling.Ignore;
                options.SerializerSettings.DateFormatString = "yyyy-MM-dd HH:mm:ss";

                //options.SerializerSettings.Converters.Add(new Newtonsoft.Json.Converters.StringEnumConverter());
                //options.SerializerSettings.Converters.Add(new Newtonsoft.Json.Converters.longconverter);
            });
        }
    }
}
